#ifndef LIGHTNING_H_
#define LIGHTNING_H_

#include "sceneObject.h"
#include "model/lighting.h"

class Lightning : public SceneObject{
	private:
		bool _visible;
		bool _stopped;
		float zRotatedAngle;
		float xRotatedAngle;

		unsigned int ticksVisible;
		unsigned int ticksFlash;
		unsigned int tickCount;

		Light* l;
	public:
		Lightning(const Cube& cube,Point sceneCenter,const ObjectModelPtr& model)
			:	SceneObject(cube,model){
			_visible=true;
			_stopped=false;
			this->zRotatedAngle=0;
			this->xRotatedAngle=0;

			ticksVisible = 8;
			ticksFlash = 5;
			tickCount=0;

			RGBAColor color(0.0f, 0.16f, 0.52f, 1.0f);
			Point dir = sceneCenter-this->dimensions.center();
			Point position(dir.x1,dir.x2,0,0);
			RGBAColor ambient(0.0f, 0.06f, 0.32f, 0.4f);

			l = Lighting::instance().createLight(position,color,ambient);
		}

		~Lightning(){
			Lighting::instance().removeLight(l);
		}

		void setModelMatrix(){
			glRotatef(this->zRotatedAngle,0,0,1);
			glRotatef(this->xRotatedAngle,1,0,0);
			SceneObject::setModelMatrix();
			if(!_visible)
				glScalef(0,0,0);
		}

		void rotate(float anglez,float anglex){
			this->zRotatedAngle += anglez;
			this->xRotatedAngle += anglex;
		}

		void setEnv(){
			glDisable(GL_LIGHTING);
			glColor4f(1.0f,1.0f,1.0f,1.0f);
			glDisable(GL_FOG);
			glEnable (GL_BLEND);
			glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			glShadeModel (GL_FLAT);
		}

		void unsetEnv(){
			glEnable(GL_LIGHTING);
			glEnable(GL_FOG);
			glDisable(GL_BLEND);
			glShadeModel (GL_SMOOTH);
		}

		bool stopped(){
			return _stopped;
		}

		void setStopped(bool state){
			_stopped=state;
			visible(!state);
		}

		void visible(bool val){
			_visible = val;
			if(_visible)
				l->enable();
			else
				l->disable();
		}

		static std::string name(){
			return "lightning";
		}

		void timeStep(){
			tickCount++;

			if(!_stopped){
				if(tickCount<ticksVisible){
					visible((tickCount/ticksFlash+tickCount%ticksFlash)%2);
				}else{
					tickCount=0;
					visible(false);
					_stopped=true;
				}
			}else{
				visible(false);
				_stopped=true;
				tickCount=0;
			}
		}
};

#endif /* LIGHTNING_H_ */
